using UnityEngine;
using System.Collections.Generic;
using UndergroundSurvival.Rooms;
using UndergroundSurvival.UI;

namespace UndergroundSurvival.Managers
{
    public class BuildingManager : MonoBehaviour
    {
        public static BuildingManager Instance { get; private set; }

        [Header("Building Settings")]
        private float gridSize = 1f;
        private LayerMask buildableLayer;
        private Color validPlacementColor = Color.green;
        private Color invalidPlacementColor = Color.red;

        [Header("UI References")]
        private RoomInfoPanel roomInfoPanel;

        private GameObject currentBuilding;
        private Room currentRoom;
        private bool isBuilding = false;
        private Vector3 lastMousePosition;
        private List<Room> builtRooms = new List<Room>();

        private void Awake()
        {
            if (Instance == null)
            {
                Instance = this;
            }
            else
            {
                Destroy(gameObject);
            }
        }

        private void Update()
        {
            if (!isBuilding || currentBuilding == null) return;

            // 更新建筑预览位置
            UpdateBuildingPreview();

            // 处理鼠标输入
            if (Input.GetMouseButtonDown(0))
            {
                TryPlaceBuilding();
            }
            else if (Input.GetMouseButtonDown(1) || Input.GetKeyDown(KeyCode.Escape))
            {
                CancelBuilding();
            }
        }

        public void SetGridSize(float size)
        {
            gridSize = size;
        }

        public void SetBuildableLayer(LayerMask layer)
        {
            buildableLayer = layer;
        }

        public void SetPlacementColors(Color valid, Color invalid)
        {
            validPlacementColor = valid;
            invalidPlacementColor = invalid;
        }

        public void SetRoomInfoPanel(RoomInfoPanel panel)
        {
            roomInfoPanel = panel;
        }

        public void StartBuilding(string roomName)
        {
            if (isBuilding) return;

            GameObject prefab = RoomPrefabManager.Instance.GetRoomPrefab(roomName);
            if (prefab == null) return;

            if (!RoomPrefabManager.Instance.HasEnoughResources(roomName))
            {
                Debug.Log("Not enough resources to build this room!");
                return;
            }

            currentBuilding = Instantiate(prefab);
            currentRoom = currentBuilding.GetComponent<Room>();
            if (currentRoom != null)
            {
                currentRoom.SetPreviewMode(true);
            }

            isBuilding = true;
            lastMousePosition = Input.mousePosition;
        }

        private void UpdateBuildingPreview()
        {
            if (currentBuilding == null) return;

            // 获取鼠标位置对应的网格位置
            Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector3 gridPosition = new Vector3(
                Mathf.Round(mousePosition.x / gridSize) * gridSize,
                Mathf.Round(mousePosition.y / gridSize) * gridSize,
                0f
            );

            // 更新预览位置
            currentBuilding.transform.position = gridPosition;

            // 检查位置是否有效
            bool isValid = IsValidPlacement(gridPosition);
            currentRoom?.SetPreviewValid(isValid);
        }

        private bool IsValidPlacement(Vector3 position)
        {
            // 检查是否与其他房间重叠
            Collider2D[] colliders = Physics2D.OverlapBoxAll(position, Vector2.one * gridSize, 0f, buildableLayer);
            foreach (var collider in colliders)
            {
                if (collider.gameObject != currentBuilding)
                {
                    return false;
                }
            }

            // 检查是否在可建造区域内
            // TODO: 添加可建造区域的检查逻辑

            return true;
        }

        private void TryPlaceBuilding()
        {
            if (currentBuilding == null || !isBuilding) return;

            Vector3 position = currentBuilding.transform.position;
            if (IsValidPlacement(position))
            {
                // 消耗资源
                RoomPrefabManager.Instance.ConsumeBuildResources(currentRoom.roomName);

                // 完成建造
                currentRoom.SetPreviewMode(false);
                currentRoom.Build();
                builtRooms.Add(currentRoom);

                // 重置状态
                currentBuilding = null;
                currentRoom = null;
                isBuilding = false;
            }
        }

        public void CancelBuilding()
        {
            if (currentBuilding != null)
            {
                Destroy(currentBuilding);
            }

            currentBuilding = null;
            currentRoom = null;
            isBuilding = false;
        }

        public void UpgradeRoom(Room room)
        {
            if (room == null || !room.isBuilt) return;

            string roomName = room.roomName;
            if (RoomPrefabManager.Instance.HasEnoughResources(roomName, true))
            {
                RoomPrefabManager.Instance.ConsumeBuildResources(roomName, true);
                room.Upgrade();
            }
        }

        public void DemolishRoom(Room room)
        {
            if (room == null || !room.isBuilt) return;

            room.Demolish();
            builtRooms.Remove(room);
            Destroy(room.gameObject);
        }

        public void ShowRoomUI(Room room)
        {
            if (roomInfoPanel != null)
            {
                roomInfoPanel.ShowRoomInfo(room);
            }
        }

        public List<Room> GetBuiltRooms()
        {
            return builtRooms;
        }
    }
} 
} 